#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion
using System.IO;
using System.Text;
using Cysharp.Threading.Tasks;
using Neatly.Helper;
using Neatly.Module;
using UnityEngine;

namespace Neatly.Load.Manager
{
    public class LuaLoadManager : Singleton<LuaLoadManager>
    {
        private LoadModule m_LoadModule;
        private Loader m_Loader;

        public async UniTask Init(LoadModule loadModule)
        {
            m_LoadModule = loadModule;
#if UNITY_WEBGL
            if (!NeatlyConfig.AssetBundleEnable) return;
            m_Loader = await m_LoadModule.LoadAssetBundleDirect(NeatlyConfig.LUA_PACKAGE);
#endif
        }

        public byte[] LoadLua(string fileName)
        {
            fileName = fileName.ToLower();
#if UNITY_WEBGL
            if (NeatlyConfig.AssetBundleEnable)
            {
                fileName = fileName.Replace('/', '_');
                return Encoding.UTF8.GetBytes(AesEncryptUtility.Decrypt(m_Loader.LoadAsset<TextAsset>(fileName).text));
            }
#endif
#if !UNITY_EDITOR
#if UNITY_STANDALONE_WIN
            if (fileName.StartsWith("game/logicmodule/data"))
            {
                string filePath = $"{GetSvnLuaPath()}/lua/{fileName.Split('/')[^1]}.lua";
                if (System.IO.File.Exists(filePath))
                {
                    return FileModule.Instance.ReadFile(filePath);
                }
            }
#endif
            fileName = fileName.Replace('/', '_');
            fileName = FileHashManager.Instance.GetFileName(NeatlyConfig.LUA_PACKAGE_64, fileName);
            byte[] luaByte = FileModule.Instance.ReadUpdateLua(fileName);
            if (luaByte != null)
            {
                return luaByte;
            }
#if UNITY_ANDROID
            string path = $"{NeatlyConfig.LUA_PACKAGE}/{fileName}";
            return Neatly.Native.AndroidHelper.ReadBytes(path);
#else
            string path = $"{UnityEngine.Application.streamingAssetsPath}/{NeatlyConfig.LUA_PACKAGE}/{fileName}";
            return FileModule.Instance.ReadFile(path);
#endif
#endif
            return FileModule.Instance.ReadEditorLua(fileName);
        }

        private string GetSvnLuaPath()
        {
            string pathSource = Application.streamingAssetsPath;
            for (int i = 0; i < 3; i++)
            {
                pathSource = Path.GetDirectoryName(pathSource);
            }
            return pathSource;
        }
    }
}